﻿package net.wangit.adm.group;

import net.wangit.MapList;
import net.wangit.Row;
import net.wangit.jdbc.DB;
import net.wangit.jdbc.DBFactory;
import net.wangit.support.TreeFactory;
import net.wangit.user.group.UserGroup;
import net.wangit.user.group.UserGroupFactory;
import net.wangit.util.Checker;
import net.wangit.view.tree.Tree;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


public class GroupTreeFactory extends TreeFactory {

	private static final Log log = LogFactory
			.getLog(net.wangit.adm.group.GroupTreeFactory.class);
	private static final String ICON_VALID = "/domain/adm/u/group1.png";
	private static final String ICON_DISABLED = "/domain/adm/u/group0.png";
	private static final String LINK_PREFIX = "/adm/group.roles.do?groupid=";
	private static final String ATTRIBUTE = "oncontextmenu=showMenu()";
	private static final String SQL = "select groupid,parentid,groupname,enabled,o from AGROUP order by o,groupid";

	public GroupTreeFactory() {
	}

	public Tree createTree(String domain) throws Exception {
		DB db = DBFactory.getDB();
		MapList data = db
				.query("select groupid,parentid,groupname,enabled,o from AGROUP order by o,groupid");
		if (Checker.isEmpty(data))
			return null;
		int rootRowIndex = data.findRowIndex("parentid", "");
		if (rootRowIndex < 0)
			rootRowIndex = data.findRowIndex("parentid", null);
		if (rootRowIndex < 0) {
			log.error("could not found the root of role");
			return null;
		} else {
			Tree tree = getTree(data, rootRowIndex);
			return tree;
		}
	}

	private Tree getTree(MapList data, int index) throws Exception {
		Tree tree = new Tree();
		Row row = data.getRow(index);
		String groupId = row.get("groupid");
		String groupName = row.get("groupname");
		UserGroup group = UserGroupFactory.getUserGroup(groupId);
		tree.setId(groupId);
		setName(tree, groupId, groupName, group.getRoles().length, group
				.getPrivileges().size());
		boolean valid = "1".equals(row.get("enabled"));
		tree.setIcon(valid ? "/domain/adm/u/group1.png"
				: "/domain/adm/u/group0.png");
		setCustomAttribute(tree, groupId);
		for (int i = 0; i < data.size(); i++) {
			String parent = data.getRow(i).get("parentid");
			if (groupId.equals(parent))
				tree.add(getTree(data, i));
		}

		return tree;
	}

	protected void setCustomAttribute(Tree tree, String groupId) {
		tree.setAttribute("oncontextmenu=showMenu()");
		tree.setAction((new StringBuilder("/adm/group.roles.do?groupid="))
				.append(groupId).toString());
	}

	protected void setName(Tree tree, String orgId, String orgName,
			int roleCount, int privilegeCount) {
		tree.setName((new StringBuilder(String.valueOf(roleCount))).append(" ")
				.append(orgName).append(" (").append(orgId).append(") ")
				.append(privilegeCount).toString());
	}

}
